package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.AttractActivityRecordFrontDetailResponse;
import com.zbkj.common.response.AttractActivityRecordFrontPageDataResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.AttractActivityRecord;
import com.zbkj.service.dao.AttractActivityRecordDao;
import com.zbkj.service.service.AttractActivityRecordService;

import com.zbkj.common.request.AttractActivityRecordFrontSaveRequest;
import com.zbkj.common.request.AttractActivityRecordSearchRequest;
import com.zbkj.common.response.AttractActivityRecordPageDataResponse;
import com.zbkj.common.response.AttractActivityRecordDetailResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.AttractActivityService;
import com.zbkj.service.service.SystemAttachmentService;
import com.zbkj.service.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author Caiyc
* @description AttractActivityRecordServiceImpl 接口实现
* @date 2025-08-07
*/
@Service
public class AttractActivityRecordServiceImpl extends ServiceImpl<AttractActivityRecordDao, AttractActivityRecord> implements AttractActivityRecordService {

    @Resource
    private AttractActivityRecordDao dao;
    @Autowired
    private UserService userService;
    @Autowired
    private AttractActivityService attractActivityService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Override
    public Boolean create(AttractActivityRecordFrontSaveRequest attractActivityRecordFrontSaveRequest) {
        AttractActivityRecord attractActivityRecord = new AttractActivityRecord();
        BeanUtils.copyProperties(attractActivityRecordFrontSaveRequest, attractActivityRecord, "id");
        boolean save = save(attractActivityRecord);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询邀约活动记录表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<AttractActivityRecord>
     * @author Caiyc
     * @since 2025-08-07
     */
    @Override
    public List<AttractActivityRecordPageDataResponse> getList(AttractActivityRecordSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<AttractActivityRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(AttractActivityRecord::getActivityId, request.getActivityId());
        lambdaQueryWrapper.eq(AttractActivityRecord::getIsDel, false);
        if (StrUtil.isNotBlank(request.getContact())) {
            lambdaQueryWrapper.like(AttractActivityRecord::getContact, request.getContact());
        }
        if (ObjectUtil.isNotNull(request.getParentUid())) {
            lambdaQueryWrapper.eq(AttractActivityRecord::getParentUid, request.getParentUid());
        }
        // 用户昵称
        if (StrUtil.isNotBlank(request.getUserName())) {
            String decode = URLUtil.decode(request.getUserName());
            List<Integer> userIds = userService.getIdsByName(decode);
            if (CollUtil.isEmpty(userIds)) {
                return new ArrayList<>();
            }
            lambdaQueryWrapper.in(AttractActivityRecord::getUid, userIds);
        }

        lambdaQueryWrapper.orderByDesc(AttractActivityRecord::getCreateTime);
        List<AttractActivityRecord> attractActivityRecords = dao.selectList(lambdaQueryWrapper);
        List<AttractActivityRecordPageDataResponse> attractActivityRecordResponses = new ArrayList<>();

        attractActivityRecords.stream().forEach(x->{
            AttractActivityRecordPageDataResponse attractActivityRecordResponse = new AttractActivityRecordPageDataResponse();
            BeanUtils.copyProperties(x, attractActivityRecordResponse);
            // 用户昵称
            LambdaQueryWrapper<User> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.select(User::getNickname, User::getPhone);
            checkWrapper.eq(User::getId, x.getUid());
            User user = userService.getOne(checkWrapper);
            if (ObjectUtil.isNotNull(user)) {
                attractActivityRecordResponse.setUserName(user.getNickname());
                attractActivityRecordResponse.setUserNamePhone(user.getPhone());
            }
            attractActivityRecordResponses.add(attractActivityRecordResponse);
        });
        return attractActivityRecordResponses;
    }

    @Override
    public PageInfo<AttractActivityRecordFrontPageDataResponse> getMyListH5(PageParamRequest pageParamRequest) {
        User user = userService.getInfo();
        Page<AttractActivityRecord> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<AttractActivityRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(AttractActivityRecord::getUid, user.getId());
        lambdaQueryWrapper.eq(AttractActivityRecord::getIsDel, false);
        lambdaQueryWrapper.orderByDesc(AttractActivityRecord::getCreateTime);
        List<AttractActivityRecord> attractActivityRecords = dao.selectList(lambdaQueryWrapper);
        List<AttractActivityRecordFrontPageDataResponse> attractActivityRecordResponses = new ArrayList<>();

        attractActivityRecords.stream().forEach(x->{
            AttractActivityRecordFrontPageDataResponse attractActivityRecordResponse = new AttractActivityRecordFrontPageDataResponse();
            BeanUtils.copyProperties(x, attractActivityRecordResponse);
            // 活动标题
            String title = attractActivityService.getTitleById(x.getActivityId());
            attractActivityRecordResponse.setTitle(title);
            attractActivityRecordResponses.add(attractActivityRecordResponse);
        });
        return CommonPage.copyPageInfo(page, attractActivityRecordResponses);
    }

    /**
    * 修改邀约活动记录表
    * @param request
    * @return
    */
    @Override
    public boolean update(AttractActivityRecordFrontSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入邀约活动记录表ID");
        }
        getByIdException(request.getId());
        AttractActivityRecord attractActivityRecord = new AttractActivityRecord();
        BeanUtils.copyProperties(request, attractActivityRecord);
        return updateById(attractActivityRecord);
    }

    private AttractActivityRecord getByIdException(Integer id) {
        AttractActivityRecord attractActivityRecord = getById(id);
        if (ObjectUtil.isNull(attractActivityRecord)) {
            throw new AppException("邀约活动记录表不存在");
        }
        if (attractActivityRecord.getIsDel()) {
            throw new AppException("邀约活动记录表不存在");
        }
        return attractActivityRecord;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
    LambdaUpdateWrapper<AttractActivityRecord> luw = Wrappers.lambdaUpdate();
        luw.set(AttractActivityRecord::getIsDel, true);
        luw.in(AttractActivityRecord::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除邀约活动记录表失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public AttractActivityRecordDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<AttractActivityRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivityRecord::getIsDel, 0);
        lqw.eq(AttractActivityRecord::getId, id);
        lqw.last("limit 1");
        AttractActivityRecord attractActivityRecord = this.getOne(lqw);
        if (ObjectUtil.isNotNull(attractActivityRecord)) {
            AttractActivityRecordDetailResponse response = new AttractActivityRecordDetailResponse();
            BeanUtils.copyProperties(attractActivityRecord, response);
            // 标题
            String title = attractActivityService.getTitleById(attractActivityRecord.getActivityId());
            response.setTitle(title);
            // 用户昵称
//            String name = userService.getNameById(attractActivityRecord.getUid());
//            response.setUserName(name);
            LambdaQueryWrapper<User> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.select(User::getNickname, User::getPhone);
            checkWrapper.eq(User::getId, attractActivityRecord.getUid());
            User user = userService.getOne(checkWrapper);
            if (ObjectUtil.isNotNull(user)) {
                response.setUserName(user.getNickname());
                response.setUserNamePhone(user.getPhone());
            }
            return response;
        }
        return null;
    }

    @Override
    public AttractActivityRecordFrontDetailResponse getDetailsH5(Integer id) {
        LambdaQueryWrapper<AttractActivityRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivityRecord::getIsDel, 0);
        lqw.eq(AttractActivityRecord::getId, id);
        lqw.last("limit 1");
        AttractActivityRecord attractActivityRecord = this.getOne(lqw);
        if (ObjectUtil.isNotNull(attractActivityRecord)) {
            AttractActivityRecordFrontDetailResponse response = new AttractActivityRecordFrontDetailResponse();
            BeanUtils.copyProperties(attractActivityRecord, response);
            return response;
        }
        return null;
    }

    @Override
    public Integer createH5(AttractActivityRecordFrontSaveRequest attractActivityRecordFrontSaveRequest) {
        User user = userService.getInfo();
        AttractActivityRecord attractActivityRecord = new AttractActivityRecord();
        BeanUtils.copyProperties(attractActivityRecordFrontSaveRequest, attractActivityRecord, "id");
        attractActivityRecord.setUid(user.getId());
        if (StrUtil.isNotBlank(attractActivityRecordFrontSaveRequest.getImage())) {
            attractActivityRecord.setImage(systemAttachmentService.clearPrefix(attractActivityRecordFrontSaveRequest.getImage()));
        }
        if (StrUtil.isNotBlank(attractActivityRecordFrontSaveRequest.getVideo())) {
            attractActivityRecord.setVideo(systemAttachmentService.clearPrefix(attractActivityRecordFrontSaveRequest.getVideo()));
        }
        // 保留上下级关系
        if (user.getSpreadUid() != null && user.getSpreadUid() > 0) {
            attractActivityRecord.setParentUid(user.getSpreadUid());
            attractActivityRecord.setLevel(1);
            // 他的上级在系统有记录
            AttractActivityRecord byUid = getByUid(attractActivityRecord.getUid(), attractActivityRecordFrontSaveRequest.getActivityId());
            if (byUid != null) {
                attractActivityRecord.setLevel(2);
            }
        }

        boolean save = save(attractActivityRecord);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return attractActivityRecord.getId();
    }

    @Override
    public int getCountByUid(Integer activityId, Integer uid) {
        LambdaQueryWrapper<AttractActivityRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivityRecord::getIsDel, 0);
        lqw.eq(AttractActivityRecord::getUid, uid);
        lqw.eq(AttractActivityRecord::getActivityId, activityId);
        return this.count(lqw);
    }

    private AttractActivityRecord getByUid(Integer uid, Integer activityId) {
        LambdaQueryWrapper<AttractActivityRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(AttractActivityRecord::getIsDel, 0);
        lqw.eq(AttractActivityRecord::getUid, uid);
        lqw.eq(AttractActivityRecord::getActivityId, activityId);
        lqw.last("limit 1");
        AttractActivityRecord attractActivityRecord = this.getOne(lqw);
        return attractActivityRecord;
    }

}

